package com.romain.risotto.entities;

import static org.andengine.extension.physics.box2d.util.constants.PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT;

import org.andengine.extension.physics.box2d.PhysicsConnector;
import org.andengine.extension.physics.box2d.PhysicsFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

import android.util.Log;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.romain.risotto.Constantes;
import com.romain.risotto.manager.GameManager;

public class Bullet extends SpaceSpriteObject {

	private float livingtime = 0;
	private final Ship origineShip;

	public int getDamageValue() {
		return Constantes.BULLET_DAMAGE_VALUE;
	}

	public Bullet(Ship origine, ITextureRegion textureBullet,
			VertexBufferObjectManager vertexBufferObjectManager) {

		super(false, 44, 44, textureBullet, vertexBufferObjectManager);
		origineShip = origine;
		float[] tab = origine.convertLocalToSceneCoordinates(origine.bulletX,origine.bulletY);
		float _x = tab[0] - this.getWidthScaled()/2 ;
		float _y =tab[1] - this.getHeightScaled()/2 ;
		this.setPosition(_x, _y);
		createBody();
		game.physicWorld.registerPhysicsConnector(new PhysicsConnector(this, body, true, false));
		direction = origine.getDirection();
		float vitesseX = origine.getSpeed().x + (float) (Constantes.BULLET_SPEED *Math.cos(direction - Math.PI / 2));
		float vitesseY = origine.getSpeed().y + (float) (Constantes.BULLET_SPEED *Math.sin(direction - Math.PI / 2));
		body.setLinearVelocity(vitesseX,vitesseY);
		
		
		//Log.d("bullet","direction:"+origine.getDirection()+"  origxy:"+tab[0]+" , "+tab[1]+"  calcxy:"+_x+" , "+_y);
	}

	@Override
	protected void onManagedUpdate(final float pSecondsElapsed) {

		livingtime += pSecondsElapsed;
		if (livingtime > Constantes.TTL_BULLET1) {
			this.delete();
			return;
		}
		//Log.d("bullet", "position: "+this.getX()+"  :  "+this.getY());

		super.onManagedUpdate(pSecondsElapsed);

	}

	@Override
	protected void createBody() {
		FixtureDef bulletFixture ;
		if(origineShip== game.getMainShip()){
			bulletFixture = GameManager.FIXTURE_MY_BULLET_DEF;
		}
		else{
			bulletFixture = GameManager.FIXTURE_OTHER_BULLET_DEF;
		}
		
		body = PhysicsFactory.createCircleBody(game.physicWorld, this, BodyType.DynamicBody, bulletFixture);
		
	}

}
